package com.wxx;

import java.util.Arrays;

/**
 * @author: Jetwang
 * @date: 2022/3/18 18:42
 * @description: GenericSelectionSort 通用选择排序
 * @version: 1.0
 */
public class GenericSelectionSort {
    /**
     * 实现通用的泛型选择排序方法 T需要实现Comparable接口的类型
     * @param arr
     * @param <T>
     */
    public static <T extends Comparable<T>> void selectionSort(T[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j].compareTo(arr[minIndex]) < 0) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    /**
     * 提取数字交换方法
     * @param arr
     * @param i
     * @param j
     */
    private static <T> void swap(T[] arr, int i, int j) {
        T temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        Integer[] arr = {2, 4, 1, 7, 3, 8, 5};
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));

        Character[] chars = {'a', 'r', 'q', 'b', 'd', 'o', 'h'};
        selectionSort(chars);
        System.out.println(Arrays.toString(chars));

        Student student01 = new Student("Jack", 75);
        Student student02 = new Student("Jet", 85);
        Student student03 = new Student("Jackson", 65);
        Student student04 = new Student("Jeffy", 70);
        Student[] students = {student01, student02, student03, student04};
        selectionSort(students);
        for (Student student : students) {
            System.out.println(student);
        }

        // 测试10000个数字的选择排序时间
        Integer[] integers = ArrayGenerator.generateRandomArray(10000, 10000);
        long startTime = System.nanoTime();
        selectionSort(integers);
        long endTime = System.nanoTime();
        double time = (endTime - startTime) / 1000000000.0;
        System.out.println(SortingHelper.isSorted(integers));
        System.out.println("耗时:" + time + "s");

    }
}
